package com.hliushi.redis.controller;

import com.hliushi.redis.config.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author llhuang10
 * @date 2021/8/14 14:17
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class TaobaoController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/taobao-draw")
    public ResponseEntity<List<String>> price(Long level) {

        List<String> result = null;

        try {
            SetOperations<String, String> setOperations = redisTemplate.opsForSet();
            switch ((int) level.longValue()) {
                case 1:
                    // spop命令, 即随机返回并删除set中一个元素
                    result = setOperations.pop(Constants.PRICE_KEY, 1);
                    break;
                case 2:
                    result = setOperations.pop(Constants.PRICE_KEY, 5);
                    break;
                case 3:
                    result = setOperations.pop(Constants.PRICE_KEY, 10);
                    break;
                default:
                    log.error("参数错误!");
            }
            log.info("查询结果: {}", result);
        } catch (Exception e) {
            log.error("exception:", e);
        }

        assert result != null;
        return ResponseEntity.ok(result);
    }
}
